<script setup lang='ts'>
import type { PlusFormGroupRow } from 'plus-pro-components'

import { useAuditByCW, useGetMemberAuditInfo } from '@fl/api/man-api'
import FlUpload from '@fl/components/fl-upload.vue'
import dayjs from 'dayjs'
import { ElLoading } from 'element-plus'
import { cloneDeep } from 'lodash-es'

const { id } = useRoute().params

const formRef = ref()

const flUpload = ref()

const { data, isLoading } = useGetMemberAuditInfo(String(id))

const { isPending: auditLoading, mutate: auditByMutate } = useAuditByCW()

const { back } = useRouter()

const loading = computed(() => isLoading.value)

const state = ref<any>({
    actType: '',
    actualPay: 0,
    actualPayDate: '',
    afterExpiration: '',
    attachment: [],
    auditStatus: '',
    createTime: '',
    enterpriseId: '',
    enterpriseName: '',
    expirationTime: '',
    levelId: '',
    memberLevelName: '',
    memberStatus: '',
    payAmount: '',
    payDate: '',
    paymentReceiptList: [],
    remark: '',
    status: 0,
})

const isAudit = computed(() => state.value.status !== 0)

const group = computed<PlusFormGroupRow[]>(() => {
    return [
        {
            columns: [
                {
                    colProps: {
                        span: 8,
                    },
                    label: '公司名称',
                    prop: 'enterpriseName',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    label: '会员等级',
                    prop: 'memberLevelName',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    label: '申请时间',
                    prop: 'createTime',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    label: '缴费金额(元)',
                    prop: 'payAmount',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    label: '缴费日期',
                    prop: 'payDate',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    label: '会员状态',
                    prop: 'memberStatus',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '有效期至',
                    prop: 'expirationTime',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '支付凭证',
                    prop: 'paymentReceiptList',
                    valueType: 'text',
                },
            ],
            title: '申请信息',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 8,
                    },
                    label: '审批意见',
                    options: [
                        {
                            label: '通过',
                            value: 0,
                        },
                        {
                            label: '不通过',
                            value: 1,
                        },
                    ],
                    prop: 'auditStatus',
                    valueType: isAudit.value ? 'text' : 'select',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    fieldProps: { max: 999999999, min: 0, precision: 2 },
                    label: '入账金额(元)',
                    prop: 'actualPay',
                    valueType: isAudit.value ? 'text' : 'input-number',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    fieldProps: {
                        disabledDate: (time: Date) => {
                            return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
                        },
                        type: 'datetime',
                        valueFormat: 'YYYY-MM-DD HH:mm:ss',
                    },
                    label: '入账时间',
                    prop: 'actualPayDate',
                    valueType: isAudit.value ? 'text' : 'date-picker',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    fieldProps: {
                        maxlength: 500,
                    },
                    label: '备注',
                    prop: 'remark',
                    valueType: isAudit.value ? 'text' : 'textarea',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '附件',
                    prop: 'attachment',
                },
            ],
            title: '财务审核',
        },

    ]
})

const rules = computed(() => {
    if (unref(state).auditStatus === 1) {
        return {
            auditStatus: [
                {
                    message: '请选择审批意见',
                    required: true,
                },
            ],
        }
    }
    return {
        actualPayDate: [
            {
                message: '请输入入账时间',
                required: true,
            },
        ],
        attachment: [
            {
                message: '请上传附件',
                required: true,
            },
        ],
        auditStatus: [
            {
                message: '请选择审批意见',
                required: true,
            },
        ],
    }
})

const MEMBER_STATUS = {
    0: '正常',
    1: '已过期',
    2: '已禁用',
}
async function mySubmit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            actualPay: state.value.actualPay,
            actualPayDate: state.value.actualPayDate,
            attachment: state.value.attachment,
            auditStatus: state.value.auditStatus,
            id: String(id),
            remark: state.value.remark,
        }
        auditByMutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                back()
            },
        })
    }
}

function showFile(file: any) {
    window.open(file)
}

watchEffect(() => {
    if (data.value) {
        const params = {
            ...data.value,
            actType: data.value.actType === 1 ? '' : data.value.actType,
            auditStatus: (data.value.status === 1 || data.value.status === 2) ? '通过' : data.value.status === 3 ? '不通过' : '',
        }
        state.value = cloneDeep(params)
    }
})

function servicesLoading(node, str, lock, bg) {
    return ElLoading.service({
 	background: bg, // 背景色与透明度
        lock, // 同v-loading的修饰符
        // loading需要覆盖的DOM节点，默认为body
        target: document.querySelector(node),
        text: str, // 加载文案
    // spinner: 'el-icon-loading',	 //加载图标
    })
}

const uploadFileStatus = ref(false)
const loadingInstance = ref<any>(null)
function uploadFileStart() {
    uploadFileStatus.value = true
    loadingInstance.value = servicesLoading('.el-dialog.upload-file-dialog', '正在上传中,请耐心等待', true, 'rgba(0,0,0,0.3)')
}
function uploadSuccess(data: any) {
    if (data.url) {
        uploadFileStatus.value = false
        setTimeout(() => {
            loadingInstance.value.close()
            ElMessage.success('图片上传成功')
        }, 1000)
    }
}
</script>

<template>
    <el-skeleton v-if="loading"
                 :rows="5"
    />

    <el-card v-else
             shadow="never"
    >
        <template #header>
            <div text-16
                 font-bold
            >
                会员审核
            </div>
        </template>

        <PlusForm ref="formRef"
                  v-model="state"
                  :group="group"
                  :row-props="{ gutter: 20 }"
                  :label-width="120"
                  :rules="isAudit ? {} : rules"
        >
            <template #plus-field-memberStatus>
                {{ MEMBER_STATUS[state?.memberStatus] ?? '会员认证' }}
            </template>

            <template #plus-field-paymentReceiptList>
                <div v-if="state.paymentReceiptList?.length"
                     text-red
                     flex
                     flex-col
                     gap-10
                     justify-center
                >
                    <div v-for="item, index in state.paymentReceiptList"
                         :key="index"
                         text
                         cursor-pointer
                         @click="showFile(item.url)"
                    >
                        {{ item.name }}
                    </div>
                </div>
            </template>

            <template #plus-field-attachment>
                <FlUpload v-if="!isAudit"
                          ref="flUpload"
                          v-model="state.attachment"
                          is-mall-admin
                          list-type="text"
                          :limit="5"
                          :file-size="50"
                          accept="*"
                          @start="uploadFileStart"
                          @success="uploadSuccess"
                />

                <div v-else>
                    <div v-if="state.attachment.length"
                         text-red
                         flex
                         flex-col
                         gap-10
                         justify-center
                    >
                        <div v-for="item, index in state.attachment"
                             :key="index"
                             text
                             cursor-pointer
                             @click="showFile(item.url)"
                        >
                            {{ item.name }}
                        </div>
                    </div>
                </div>
            </template>

            <template #footer>
                <div style="margin: 0 auto">
                    <el-button v-if="!isAudit"
                               type="primary"
                               :loading="auditLoading"
                               @click="mySubmit"
                    >
                        提交
                    </el-button>

                    <el-button @click="back">
                        返回
                    </el-button>
                </div>
            </template>
        </PlusForm>
    </el-card>
</template>
